﻿<%@ WebHandler Language="C#" Class="App_User" %>
using System;
using System.Web;
using System.Web.SessionState;
using System.Web.Security;
using NetDimension.Weibo;
using System.Configuration;
public class App_User : IHttpHandler, IRequiresSessionState
{

    string msg = string.Empty;
    readonly Users Users = new Users();
    readonly WinLog WinLog = new WinLog();
    public void ProcessRequest(HttpContext context)
    {
        CurrentContext = context;
        try
        {
            string action = context.Request.QueryString["action"].ToString();
            string tel = string.Empty;
            string pwd = string.Empty;
            string udid = string.Empty;
            string smscode = string.Empty;
            string icon = string.Empty;    
            string token = string.Empty;
            string wbaccount = string.Empty;
            string email=string.Empty;
            udid = GetQuery("udid");
            
            //PC端使用参数
            string realname = string.Empty;
            string sex = string.Empty;  
            
            switch (action.ToLower())
            {
                case "getcode":
                    tel = GetQuery("tel");
                    SendRegSMS(tel);
                    break;
                case "login":
                    tel = GetQuery("tel");
                    pwd = GetQuery("pwd");
                    Login(tel, pwd, udid);
                    break;
                case "regist":
                    tel = GetQuery("tel");
                    pwd = GetQuery("pwd");
                    smscode = GetQuery("code");
                    //realname = GetQuery("realname");
                    //sex = GetQuery("sex");
                    RegistForPhone(tel, pwd, udid, smscode);
                    //msg = "{\"result\":\"error\",\"msg\":\"活动已结束\"}";
                    break;
                case "pcregist":
                    tel = GetQuery("tel");
                    pwd = GetQuery("pwd");
                    smscode = GetQuery("code");
                    realname = GetQuery("realname");
                    //sex = GetQuery("sex");
                    RegistForPC(tel, pwd,realname, udid, smscode);
                    //msg = "{\"result\":\"error\",\"msg\":\"活动已结束\"}";
                    break;
                 case "update":
                    token = GetQuery("token");
                    sex = GetQuery("sex");
                    realname = GetQuery("rname");
                    email = GetQuery("email");
                    icon = GetQuery("icon");
                    Update(token,realname,sex,email,udid,icon);
                    //msg = "{\"result\":\"error\",\"msg\":\"活动已结束\"}";
                    break;
                 case "updatetel":
                    token = GetQuery("token");
                    tel = GetQuery("tel");
                     smscode = GetQuery("code");
                    UpdateTel(token, tel, smscode, udid);
                   
                    break;
                case "changepwd":
                    token = GetQuery("token");
                    pwd = GetQuery("pwd");
                    ChangePwd(token, pwd, udid);
                    break;
                case "info":
                    token = GetQuery("token");
                    GetInfo(token, udid);
                    break;
                case "upimg":
                    token = GetQuery("token");
                    UpImg(token, udid);
                    break;
                case "weibologin":
                    wbaccount = GetQuery("wbaccount");                 
                    WBLogin(wbaccount, udid);
                    break;
                case "getpwd":
                    tel = GetQuery("tel");
                    GetPwd(tel,udid);
                    break;
                case "pcgowb":

                    PCGoWB();
                    break;
                
            }
        }
        catch (Exception err)
        {
            msg = "{\"result\":\"error\",\"msg\":\"" + err.Message + "\"}";
        }
        finally
        {
            context.Response.Write(msg);
        }
    }
    public HttpContext CurrentContext;
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }


    public string GetQuery(string name)
    {
        string res = string.Empty;
        if (CurrentContext.Request.QueryString[name] != null)
            res = CurrentContext.Request.QueryString[name].ToString();
        return res;
    }
    /// <summary>
    /// 发送注册短信
    /// </summary>
    /// <param name="tel"></param>
    public void SendRegSMS(string tel)
    {
        if (string.IsNullOrEmpty(tel))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else
        {
            try
            {

                if (!Users.ExistByTel(tel))
                {
                    string senderrnsg = string.Empty;
                    if(!SMS.SendRegCode(tel,out senderrnsg))
                        msg = "{\"result\":\"error\",\"msg\":\""+senderrnsg+"\"}";
                    else
                        msg = "{\"result\":\"success\"}";
                    
                }
                else
                {
                    msg = "{\"result\":\"error\",\"msg\":\"该手机号已经注册\"}";
                }

            }
            catch (Exception error)
            {
                msg = "{\"result\":\"error\",\"msg\":\"" + error.Message + "\"}";
            }
        }
    }
    public void RegistForPhone(string tel, string pwd, string udid, string smscode)
    {
        if (string.IsNullOrEmpty(tel) || string.IsNullOrEmpty(pwd) || string.IsNullOrEmpty(smscode))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else
        {
            if (!Users.ExistByTel(tel))
            {
                if (smscode.ToLower() == SMS.GenRegCode(tel).ToLower())
                {
                    string token = string.Empty;
                    if (Users.RegisterForPhone(tel, pwd, udid, CurrentContext.Request.UserHostAddress, "", out token))
                    {
                        msg = "{\"result\":\"success\",\"token\":\"" + token + "\",\"msg\":\"注册成功\"}";
                        WinLog.Create(WinLog.LOGIN_REGIST, token, "注册积分", "手机注册获取积分");
                    }
                    else
                        msg = "{\"result\":\"error\",\"msg\":\"注册失败\"}";
                }
                else
                    msg = "{\"result\":\"error\",\"msg\":\"短信验证码有误\"}";
            }
            else
            {
                msg = "{\"result\":\"error\",\"msg\":\"该手机已经注册\"}";
            }

        }
    }

    public void RegistForPC(string tel, string pwd,string realname, string udid, string smscode)
    {
        if (string.IsNullOrEmpty(tel) || string.IsNullOrEmpty(pwd) || string.IsNullOrEmpty(smscode) || string.IsNullOrEmpty(realname))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else
        {
            if (!Users.ExistByTel(tel))
            {
                if (smscode.ToLower() == SMS.GenRegCode(tel).ToLower())
                {
                    string token = string.Empty;
                    if (Users.RegisterForPC(tel, pwd, udid, CurrentContext.Request.UserHostAddress, "", realname, out token))
                    {
                        msg = "{\"result\":\"success\",\"token\":\"" + token + "\",\"msg\":\"注册成功\"}";
                        WinLog.Create(WinLog.LOGIN_REGIST, token, "注册积分", "PC注册获取积分");
                    }
                    else
                        msg = "{\"result\":\"error\",\"msg\":\"注册失败\"}";
                }
                else
                    msg = "{\"result\":\"error\",\"msg\":\"短信验证码有误\"}";
            }
            else
            {
                msg = "{\"result\":\"error\",\"msg\":\"该手机已经注册\"}";
            }

        }
    }

    public void Login(string tel, string pwd, string udid)
    {
        if (string.IsNullOrEmpty(tel) || string.IsNullOrEmpty(pwd))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else
        {
            string md5pwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "MD5");
            string token =string.Empty;
            string uname=string.Empty;
            string icon=string.Empty;
            string points=string.Empty;
            string email=string.Empty;
            string sex = string.Empty;
            string mpoints = string.Empty;
            if (Users.CheckLogin(tel,md5pwd,ref token,ref uname,ref icon,ref points,ref email,ref sex))
            {
                mpoints = GetCurrentMonthCoin(token, DateTime.Now.Month.ToString());
                msg = "{\"result\":\"success\",\"token\":\"" + token ;
                msg += "\",\"tel\":\"" + tel ;
                msg += "\",\"uname\":\"" + uname ;
                msg += "\",\"sex\":\"" + sex;
                msg += "\",\"icon\":\"" + icon; 
                msg += "\",\"points\":\"" + points;
                msg += "\",\"mpoints\":\"" + mpoints; 
                msg+= "\"}";
                if (!WinLog.ExistByToday(token, "登录积分"))//每天登陆可以获取一次
                    WinLog.Create(WinLog.LOGIN_POINT, token, "登录积分", "每日登陆获取5积分");
            }
            else
                msg = "{\"result\":\"error\",\"msg\":\"手机或密码错\"}";
        }
    }

    public string GetCurrentMonthCoin(string token, string month)
    {
        string temp = "0";
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append(" select ");
        sb.Append(" datepart(month,CTime) as MonthAt,sum(Point) as Point, uid ");
        sb.Append(" from Users_WinLog uw  ");
        sb.AppendFormat(" where Token='{0}' and datepart(month,CTime)={1} ", token, month);
        sb.Append(" group by datepart(month,CTime),uid ");

        System.Data.DataTable dt= Gomye.DataUtility.SqlRunner.DoSqlTable(sb.ToString());
        if (dt.Rows.Count > 0)
        {
            temp = dt.Rows[0]["Point"].ToString();
        }
        
        return temp;
    }
    
    public void ChangePwd(string token, string pwd, string udid)
    {
        if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(pwd))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else if(Users.Exist(token))
            if (Users.ChangePwd(token, pwd))
                msg = "{\"result\":\"success\"}";
            else
                msg = "{\"result\":\"error\",\"msg\":\"修改失败\"}";
        else
            msg = "{\"result\":\"error\",\"msg\":\"用户不存在\"}";
            
    }
    
    public void Update(string token, string realname, string sex, string email, string udid,string icon)
    {
        string imgurl = icon;
        if (string.IsNullOrEmpty(token))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else if (Users.Exist(token))
        {
            if (CurrentContext.Request.Files.Count > 0)
            {
                
                //CurrentContext.Response.ContentType = "text/plain";
                HttpFileCollection uploadedFiles = CurrentContext.Request.Files;
                HttpPostedFile file = uploadedFiles[0];
                string filename = DateTime.Now.ToString("yyyyMMddHHmmss");
                filename += "icon_" + file.FileName + ".jpg";
                string path =string.Format("/UserProfile/{0}/", token);
                if (!System.IO.Directory.Exists( CurrentContext.Server.MapPath(path)))
                    System.IO.Directory.CreateDirectory( CurrentContext.Server.MapPath(path));
                file.SaveAs(CurrentContext.Server.MapPath(path) + filename);

                imgurl = string.Format("http://{0}{1}{2}", CurrentContext.Request.Url.Host, path, filename);
            }
            bool successupdate = false;
            if (String.IsNullOrEmpty(imgurl))//没传图片则不更新头像
                successupdate = Users.UpdateInfo(token, email, realname, sex);
            else
                successupdate = Users.UpdateInfo(token, email, realname, imgurl, sex);



            if (successupdate)
            {
                if (string.IsNullOrEmpty(imgurl))
                {
                    msg = "{\"result\":\"success\",\"msg\":\"成功\"}";
                   
                }
                else
                    msg = "{\"result\":\"success\",\"url\":\"" + JSON.CoatnvertJson(imgurl) + "\"}";
                if (!WinLog.Exist(token, "更新个人资料积分"))//每天登陆可以获取一次
                    WinLog.Create(WinLog.LOGIN_UPDATE, token, "更新个人资料积分", "更新个人资料积分");
            }
            else
                msg = "{\"result\":\"error\",\"msg\":\"修改失败\"}";
        }
        else
            msg = "{\"result\":\"error\",\"msg\":\"用户不存在\"}";
            
    }
    public void GetPwd(string tel,  string udid)
    {
        if (string.IsNullOrEmpty(tel))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else
        {
            if (Users.ExistByTel(tel))
            {
                string strpwd = Users.GetPwdByTel(tel);
                string errmsg = string.Empty;
                if (SMS.SendPwd(tel, strpwd, out errmsg))
                    msg = "{\"result\":\"success\"}";
                else
                    msg = "{\"result\":\"error\",\"msg\":\"发送失败："+errmsg+"\"}";
            }
            else
                msg = "{\"result\":\"error\",\"msg\":\"用户不存在\"}";
        }

    }
    public void UpdateTel(string token,string Tel, string smscode, string udid)
    {
        
        if (string.IsNullOrEmpty(token))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else if (Users.Exist(token))
        {
            if (smscode == SMS.GenRegCode(Tel))
            {
                if (Users.UpdateTel(token, Tel))
                    msg = "{\"result\":\"success\"}";
                else
                    msg = "{\"result\":\"error\",\"msg\":\"修改失败\"}";
            }
            else
                msg = "{\"result\":\"error\",\"msg\":\"验证码错误\"}";
        }
        else
            msg = "{\"result\":\"error\",\"msg\":\"用户不存在\"}";

    }
    
    public void GetInfo(string token, string udid)
    {
       
        if (string.IsNullOrEmpty(token))//|| string.IsNullOrEmpty(udid)
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";

        }
        else
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            string sql=string.Format(" Token ='{0}'",token);
            string mpoints = string.Empty;
            int count=0;
            dt = Users.GetList(sql, 1, 1, ref count);
            if (dt.Rows.Count > 0)
            {
                mpoints = GetCurrentMonthCoin(token, DateTime.Now.Month.ToString());
                msg = "{\"result\":\"success\",\"data\":[\"uname\":\"" + dt.Rows[0]["UName"].ToString();
                msg += "\",\"icon\":\"" + dt.Rows[0]["ICon"].ToString();
                msg += "\",\"tel\":\"" + dt.Rows[0]["Tel"].ToString();
                msg += "\",\"sinaname\":\"" + dt.Rows[0]["SinaId"].ToString();
                msg += "\",\"mpoints\":\"" + mpoints;
                //DateTime tt = DateTime.Parse(dt.Rows[0]["JoinTime"].ToString());
                //msg += "\",\"jointime\":\"" + tt.ToString("yyyy-MM-dd HH:mm:ss");
                msg += "\",\"points\":\"" + dt.Rows[0]["Point"].ToString() + "\"}";

            }
            else
                msg = "{\"result\":\"error\",\"msg\":\"无此用户信息\"}";
        }
    }

    public void UpImg(string token, string udid)
    {
        Guid t = new Guid(token);
        if (string.IsNullOrEmpty(token))//|| string.IsNullOrEmpty(udid)
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";

        }
        else
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            string sql = string.Format(" Token ='{0}'", token);
            int count = 0;
            dt = Users.GetList(sql, 1, 1, ref count);
            if (dt.Rows.Count > 0)
            {
                //**上传图片
                if (CurrentContext.Request.Files.Count > 0)
                {
                    //CurrentContext.Response.ContentType = "text/plain";
                    HttpFileCollection uploadedFiles = CurrentContext.Request.Files;
                    HttpPostedFile file = uploadedFiles[0];
                    string filename = DateTime.Now.ToString("yyyyMMddHHmmss");
                    filename += "_" + file.FileName + ".jpg";
                    string path =string.Format("/UserProfile/{0}/", dt.Rows[0]["Uid"].ToString());
                    if (!System.IO.Directory.Exists( CurrentContext.Server.MapPath(path)))
                        System.IO.Directory.CreateDirectory( CurrentContext.Server.MapPath(path));
                    file.SaveAs( CurrentContext.Server.MapPath(path) + filename);

                    msg = "{\"result\":\"success\",\"url\":\"" + string.Format("http://{0}{1}{2}", CurrentContext.Request.Url.Host, path, filename) + "\"}";
                }
                else
                {
                    msg = "{\"result\":\"error\",\"msg\":\"没有发现图片文件\"}";
                }
                ////WriteLog("postStr:" + postStr);

            }
            else
            {
                
                msg = "{\"result\":\"error\",\"msg\":\"无此用户信息\"}";
            }
        }

    }

    public void WBLogin(string wbacount, string udid)
    {
        if (string.IsNullOrEmpty(wbacount))
        {
            msg = "{\"result\":\"error\",\"msg\":\"参数不能为空\"}";
        }
        else
        {

            string token = string.Empty;
            string tel = string.Empty;
            string uname = string.Empty;
            string icon = string.Empty;
            string points = string.Empty;
            string email = string.Empty;
            string sex = string.Empty;
            string mpoints = string.Empty;
            if (Users.CheckWbLogin(wbacount, ref tel, ref token, ref uname, ref icon, ref points, ref email, ref sex))//**userHelper.CheckLogin(email, md5pwd, ref token)
            {
                mpoints = GetCurrentMonthCoin(token, DateTime.Now.Month.ToString());
                
                msg = "{\"result\":\"success\",\"token\":\"" + token;
                msg += "\",\"tel\":\"" + tel;
                msg += "\",\"uname\":\"" + uname;
                msg += "\",\"sex\":\"" + sex;
                msg += "\",\"icon\":\"" + icon;
                msg += "\",\"points\":\"" + points;
                msg += "\",\"mpoints\":\"" + mpoints;
                msg += "\"}";
            }
            else
            {
                if (Users.RegisterForPhone("", "", udid, CurrentContext.Request.UserHostAddress, wbacount, out token))
                {
                    msg = "{\"result\":\"success\",\"token\":\"" + token;
                    msg += "\",\"tel\":\"" + tel;
                    msg += "\",\"uname\":\"" + uname;
                    msg += "\",\"icon\":\"" + icon;
                    msg += "\",\"points\":\"" + points;
                    msg += "\"}";
                }
                else
                    msg = "{\"result\":\"error\",\"msg\":\"登录失败\"}";
            }
        }
    }


    /// <summary>
    /// pc版微博登录借口，包括登陆请求和Callback响应
    /// </summary>
    public void PCGoWB()
    {
        OAuth oauth = new OAuth(ConfigurationManager.AppSettings["AppKey"], ConfigurationManager.AppSettings["AppSecret"], ConfigurationManager.AppSettings["CallbackUrl"]);
        string wbcode = GetQuery("code");
        if (string.IsNullOrEmpty(wbcode))
        {
           
            string url = oauth.GetAuthorizeURL(ResponseType.Code, null, DisplayType.Default);
            CurrentContext.Response.Redirect(url);
        }
        else
        {
            try
            {
                string accessToken = "";
                AccessToken sinatoken = oauth.GetAccessTokenByAuthorizationCode(wbcode);
                accessToken = sinatoken.Token;

                Client sina = new Client(new OAuth(ConfigurationManager.AppSettings["AppKey"], ConfigurationManager.AppSettings["AppSecret"], accessToken, null));


                NetDimension.Weibo.Entities.user.Entity myInfo = sina.API.Users.Show(sina.API.Account.GetUID(), null);

                string token = string.Empty;
                string tel = string.Empty;
                string uname = string.Empty;
                string icon = string.Empty;
                string points = string.Empty;
                string email = string.Empty;
                string sex = string.Empty;
                if (Users.CheckWbLogin(myInfo.ID, ref tel, ref token, ref uname, ref icon, ref points, ref email, ref sex))//**userHelper.CheckLogin(email, md5pwd, ref token)
                {

                   // msg = "ok" + token;
                    CurrentContext.Response.Cookies["zy_token"].Value =token;
                    CurrentContext.Response.Cookies["zy_uname"].Value =HttpUtility.UrlEncode(uname);
                    CurrentContext.Response.Cookies["zy_sex"].Value = sex;
                    CurrentContext.Response.Cookies["zy_icon"].Value = icon;
                    CurrentContext.Response.Cookies["zy_tel"].Value = tel;
                    CurrentContext.Response.Cookies["zy_points"].Value = points;
                    //msg += "<script src=\"/public/js/jquery.1.72.js\"></script>";
                    //msg += "<script src=\"/public/js/jquery.cookie.js\"></script>";

                    msg += "<script language='javascript'>";
                    //msg += "$.cookie('zy_token'," + token + ",{ expires: 7,path: '/'  });";
                    ////msg += "$.cookie('zy_uname'," + uname + ",{ expires: 7,path: '/'  });";
                    ////msg += "$.cookie('zy_sex',"+sex+",{ expires: 7,path: '/'  });";
                    //msg += "$.cookie('zy_icon',"+icon+",{ expires: 7 ,path: '/' });	";
                    //msg += "$.cookie('zy_tel',"+tel+",{ expires: 7,path: '/'  });";
                    //msg += "$.cookie('zy_points',"+points+",{ expires: 7 ,path: '/' });";
                    msg += "location.href='/';";
                    msg += "</script>";
                }
                else
                {
                    if (Users.RegisterForPC("", "fromsina", "", CurrentContext.Request.UserHostAddress, myInfo.ID, myInfo.ScreenName,myInfo.AvatarLarge, out token))
                    {
                        msg = "ok-regist" + token;
                        CurrentContext.Response.Cookies["zy_token"].Value = token;
                        CurrentContext.Response.Cookies["zy_uname"].Value = HttpUtility.UrlEncode(myInfo.ScreenName);
                        CurrentContext.Response.Cookies["zy_sex"].Value = "";
                        CurrentContext.Response.Cookies["zy_icon"].Value = myInfo.AvatarLarge;
                        CurrentContext.Response.Cookies["zy_tel"].Value = "";
                        CurrentContext.Response.Cookies["zy_points"].Value = WinLog.LOGIN_REGIST.ToString();
                        //msg += "<script src=\'/public/js/jquery.1.72.js\'></script>";
                        //msg += "<script src=\'/public/js/jquery.cookie.js\'></script>";
                        msg += "<script language=\"javascript\">";
                        //msg += "$.cookie(\'zy_token\'," + token + ",{ expires: 7,path: \'/\'  });";
                        //msg += "$.cookie(\'zy_uname\'," + myInfo.ScreenName + ",{ expires: 7,path: \'/\'  });";
                        ////msg += "$.cookie('zy_sex'," + sex + ",{ expires: 7,path: '/'  });";
                        //msg += "$.cookie(\'zy_icon\'," + myInfo.AvatarLarge + ",{ expires: 7 ,path: \'/\' });	";
                        ////msg += "$.cookie('zy_tel'," ",{ expires: 7,path: '/'  });";
                        //msg += "$.cookie(\'zy_points\'," + WinLog.LOGIN_REGIST.ToString() + ",{ expires: 7 ,path: \'/\' });";
                        msg += "location.href='/user/settings.shtml';";
                        msg += "</script>";
                    }
                    else
                        msg = "登陆失败"; 
                }
            }
            catch(Exception err)
            {
                msg = "登陆失败" + err.Message;
            }
            finally
            {
                 
            }
        }
       
    }
    
   
}
